/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

var FileListMenu = new Ext.menu.Menu();
var fileListEditorWindows = new Array();
var upWarnShow = true;

function createTotalColumn(value, p, record) {
	return (record.data.translated+record.data.untranslated+record.data.fuzzy);
}

var DefFile = Ext.data.Record.create([
	{name: 'id'},
	{name: 'fileName',type:'string',mapping:'name'},
	{name: 'comment',type:'string'},
	{name: 'statusId',type:'string',mapping:'statusid'},
	{name: 'translator',type:'string',mapping:'userid'},
	{name: 'reviewer',type:'string',mapping:'userid2'},
	{name: 'teamId',type:'string',mapping:'teamid'},
	{name: 'lastUpdate',type:'string',mapping:'lastupdate'},
	{name: 'translated',type:'int'},
	{name: 'untranslated',type:'int'},
	{name: 'fuzzy',type:'int'},
	{name: 'prjname',type:'string',sortField:'prjid'},
	{name: 'chstamp',type:'string'}
]);
		    
var fileStatusTransDs = new Ext.data.JsonStore({
    url: getMainUrl(),
    method: 'POST',
    baseParams: {action: 'system_list', op: "assign_trans"},
    autoLoad: false,
    root: 'results',
    id:'id',
    fields:[
     	{name: 'id' },
        {name: 'text', mapping: 'id', convert: translate }
    ]
});
var fileStatusRevDs = new Ext.data.JsonStore({
    url: getMainUrl(),
    method: 'POST',
    baseParams: {action: 'system_list', op: "assign_rev"},
    autoLoad: false,
    root: 'results',
    id:'id',
    fields:[
     	{name: 'id' },
        {name: 'text', mapping: 'id', convert: translate }
    ]
});

var fileListGrants = "";

function updateFileRow(store,list) {
	for (var i=0;i<list.length;i++) {
		var r = store.getById(list[i].id);
		if (r!=undefined) {
			r.beginEdit();
			r.set('comment',list[i].comment);
			r.set('statusId',list[i].statusid);
			r.set('translator',list[i].userid);
			r.set('reviewer',list[i].userid2);
			r.set('lastUpdate',list[i].lastupdate);
			r.set('translated',list[i].translated);
			r.set('untranslated',list[i].untranslated);
			r.set('fuzzy',list[i].fuzzy);
			r.set('chstamp',list[i].chstamp);
			r.commit();
		}
	}
}

function freeSelected(grid, pid) {
	var selections = grid.selModel.getSelections();
	if (selections.length>0) {
		var util = new Verbum.Utilities();
		util.ask({
			title: _('Add comment'),
			msg: _('Enter a comment (optional)')
		})

		util.on({
			'press_ok': function(text) {
				  	var encoded_array = "[";
				  	for(i = 0; i<selections.length; i++){
				  		var ss = "{\"id\":\"" +selections[i].get('id') + "\",\"hash\":\"" + selections[i].get('chstamp') + "\"}";
						if (i==0) {
							encoded_array = encoded_array + ss;
						} else {
							encoded_array = encoded_array + "," + ss;
						}
				  	}
				  	encoded_array = encoded_array + "]";
			
				  	var utilq = new Verbum.Utilities();
					utilq.request({
						el: grid.getEl(),
			            params: { 
			               action: "file_list", 
			               ids:  encoded_array,
			               op: 'free',
			               pid: pid,
			               comment: text
			              }											
					});
			
					utilq.on({
						'done': function(response) {
			            	obj = Ext.util.JSON.decode(response.responseText);
			            	if (obj.ret!=undefined) {
								updateFileRow(grid.getStore(),obj.ret.results);
			            	}
						},
						'fail': function(response) {
			                obj = Ext.util.JSON.decode(response.responseText); 
			            	if (obj.ret!=undefined) {
			            		updateFileRow(grid.getStore(),obj.ret.results);
			            	}
						}
					});		                	
			}
		})
	} else {
		Ext.Msg.message(_('Please, select an item from the list.'));
	}
}
function editSelected(grid, rowIndex, desktop, filePid, store) {
	var editWin = new Verbum.list.EditWindow({grid: grid, selected: rowIndex, desktop: desktop, filePid: filePid});
	
	editWin.on({
		'success': {
			fn: function (list){
				updateFileRow(store,list);
			}
		},
		'unassigned': {
			fn: function (scope) {
				showAssignWindow(scope.grid, scope.desktop, scope.filePid);
			}
		}
	});
	
	editWin.show();

}

function checkRO(pid) {
	if (readOnly[pid]) {
		Ext.Msg.warn(_('Sorry, this project is read only.'));
		return false;
	} else {
		return true;
	}
}

function showAssignWindow(grid, desktop, filePid) {
	
	var assignWin = new Verbum.list.AssignWindow({fileList: grid, desktop: desktop, filePid: filePid});
      
	assignWin.on({
		'refresh': {
			fn: function (list){
					updateFileRow(grid.getStore(),list);
			}
		}
	});

	assignWin.show();
	
}														
					
function onFileListContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    grid.selModel.selectRow(rowIndex);
    var filePid = this.filePid;
    var ds = this.ds;
    var desktop = this.desktop;
    
    var listContextMenu = new Ext.menu.Menu({
    	items: [
    		{
    			iconCls: 'history',
    			text: _('View History'),
    			handler: function() {
    				showFileHistory(grid,rowIndex,filePid);
    			}
    		},{
    			iconCls: 'svnview',
    			text: _('Open SVN History'),
    			handler: function() {
    				var id = grid.selModel.getSelected().json.id;
    				window.open("?action=svn&pid="+filePid+"&id="+id);
    			}
    		}
    		,"-",
    		{
    			iconCls: 'edit',
    			text: _('Update Status'),
    			handler: function() {
    				if (checkRO(filePid)) {
	    				editSelected(grid, rowIndex, desktop, filePid, ds);
    				}
    			}
    		},
    	]
    });
    
    listContextMenu.showAt(e.getXY());
}

Ext.ns("Verbum.list");

Verbum.list.AssignWindow = function(config){
    Ext.apply(this, config,{url: getMainUrl('action=file_list')});
    this.addEvents({
        'refresh' : true,
    });
    Verbum.list.AssignWindow.superclass.constructor.call(this);
};

Verbum.list.EditWindow = function(config){
    Ext.apply(this, config,{url: getMainUrl('action=file_list')});
    this.addEvents({
        'success' : true,
        'failure' : true,
        'unassigned': true,
    });
    Verbum.list.EditWindow.superclass.constructor.call(this);
};
/* ----------------------------- UPLOAD PANEL ------------------------------------*/
Verbum.list.UploadPanel = function(config){
    Ext.apply(this, config, {pid:''});
    this.addEvents({
        'success' : true,
        'failure' : true,
    });
    Verbum.list.UploadPanel.superclass.constructor.call(this);
};

Ext.extend(Verbum.list.UploadPanel, Ext.util.Observable, {

	getDataStore: function() {
		
		if (!this.uploadDS) {
			this.uploadDS = new Ext.data.Store({
				pruneModifiedRecords: true,
				proxy: new Ext.data.HttpProxy({
					url: getMainUrl(),
					method: 'POST'
					}),
					baseParams: {action: 'upload_control', id: this.uploadId},
					reader: new Ext.data.JsonReader({
						root: 'results',
						id: 'id',
						totalProperty: 'totalCount',
					},[
					{name: 'statusId',type:'string',mapping:'statusid'},
					{name: 'fileName',type:'string',mapping:'name'},
					{name: 'project',type:'string',mapping:'path'},
					{name: 'error',type:'string',mapping:'msg'},
					])
				});
		}

		return this.uploadDS;
	},

	getColumnModel: function() {

		if (!this.uploadCM) {
			this.uploadCM = new Ext.grid.ColumnModel(
					[
					{
						header: _('File'),
						readOnly: true,
						dataIndex: 'fileName',
						hidden: false,
						renderer: fileErrorRender,
						width: 300
					},{
						header: _('Project'),
						readOnly: true,
						dataIndex: 'project',
						hidden: false
					},					
					]
			);
			
			this.uploadCM.defaultSortable = false;
		}
		
		return this.uploadCM;
	},
	
	getUploadToolbar: function() {
	
		if (!this.uploadTB) {
			var parent = this;
			this.uploadTB = new Ext.Toolbar({
				            items:[{
				                text: _('Confirm'),
				                tooltip: _('Confirm and send files'),
				                cls: 'x-btn-text-icon ok-button',
				                handler: function(btn, pressed) {
				                		if (parent.getDataStore().getCount()==0) {
				                			Ext.Msg.message(_('There are no items to confirm.'));
				                		} else {
									        Ext.Msg.confirm(_('Confirm'),
									        	_('Do you want to confirm and send the files marked as valid?'),
									        			function(btn) {
															if (btn=="yes") {
															
																var upWindow = Ext.ComponentMgr.get(parent.winname);
																
																var util = new Verbum.Utilities();
																util.ask({
																	title: _('Add comment'),
																	msg: _('Enter a comment'),
																	allowBlank: false
																})
																																
																util.on({
																	'done': function() {
																		upWindow.hide(null);
																		upWindow.destroy();
																		parent.fireEvent("success",parent);
																	},
																	'press_ok': function(text) {
																		util.request({
																			el: upWindow.getEl(),
																            params: { 
																               action: "upload_control", 
																               id: parent.uploadId,
																               op: 'ok',
																               comment: text
																              }											
																		});
																	}
																});																
				
															} 
														} 
												);
										}				                		
				                	}
		    					},"-", {
				                text: _('Cancel'),
				                cls: 'x-btn-text-icon cancel-button',
				                tooltip: _('Abort and discard the files'),
				                handler: function(btn, pressed) {
				                		parent.close();
								}}]
				        });
		
		}
		
		return this.uploadTB;
	},
	
	getUploadGrid: function() {

		return new Ext.grid.GridPanel({
			id: 'uploadGrid',
			region: 'center',
			loadMask: {msg: _('Loading...')},
			store: this.getDataStore(),
			cm: this.getColumnModel(),
			bbar: this.getUploadToolbar(),
			view: new Ext.grid.GridView({
					forceFit:true,
            		enableRowBody:true,
            		getRowClass : function(record, rowIndex, p, store) {
            			//if (record.data.error!="")
                   			p.body = "<span class=\"grid-up-err-msg\">"+record.data.error+"</span>";
            		 }
				}),
		});
	
	},

	getUploadPanel: function() {

		if (!this.upPanel) {
			if (BrowserDetect.browser == "Opera") {
				this.upPanel = new Ext.FormPanel({
				        region: 'north',
				        fileUpload: true,
				        url: getMainUrl(),
				        baseParams: {pid: this.pid, action: 'upload_file', id: this.uploadId, mode: 'single'},
				        autoHeight: true,
				        frame: false,
				        bodyStyle: 'padding: 5px 5px 0 5px;',
				        waitMsgTarget: this.winname,
				        labelWidth: 50,
				        items:[{
				        	layout:'table',
				        	border: false,
					        items: [{
					        	border: false,
					        	items: [{
						            xtype: 'textfield',
						            inputType: 'file',
						            name: 'files',
						            hideLabel: true,
						            allowBlank: false,
						            }]
					        	},{
					        	items: [{
						        	xtype: 'button',
						            text: _('Upload'),
						            scope: this,
						            iconCls: 'icon-upload',
						            handler: function(){
						            	var panel = this.upPanel;
						                if(this.upPanel.getForm().isValid()){
							                this.upPanel.getForm().submit({
							                    waitMsg: _('Uploading, please wait...'),
							                    success: function(frm, resp){
							                        panel.fireEvent("allfinished");
							                    },
							                    failure:function(frm, resp){ 
							                    	Ext.Msg.error(resp.result.errors.files);
							                    }
							                });
						                }
						            }
								}]
					        }]
				        }]
				    });
				this.upPanel.addEvents('allfinished');		    
 			} else {
				this.upPanel = new Ext.ux.UploadPanel({
					region: 'west',
					buttonsAt:'tbar',
					url: getMainUrl(),
					maxFileSize: MAX_FILE_SIZE,
					singleUpload: true,
					split: true,
					baseParams: {pid: this.pid, action: 'upload_file', id: this.uploadId},
					height:220,
					minWidth: 180,
					width: 180,
					enableProgress: false,
					clickRemoveText: _('Click to remove'),
					emptyText: _('No files'),
					errorText: _('Error'),
					fileQueuedText: _('File <b>{0}</b> is queued for upload'),
					fileDoneText: _('File <b>{0}</b> has been successfully uploaded'),
					fileFailedText: _('File <b>{0}</b> failed to upload'),
					fileUploadingText: _('Uploading file <b>{0}</b>'),
					removeAllText: _('Remove All'),
					removeText: _('Remove'),
					uploadText: _('Upload'),
					addText: _('Add'),
					uploadText: _('Upload')
				});
			}
		}
		
		return this.upPanel;
	
	},

	close: function () {
		var upWindow = Ext.ComponentMgr.get(this.winname);	
		if (upWindow) {
			upWindow.close();
		}	
	},

	cancel: function(win) {
		Ext.Ajax.request({ 
            url: getMainUrl(), 
            params: { 
               action: "upload_control",
               id: win.parent.uploadId,
               op: "cancel"
              }, 
            success: function(response){
            },
	   	});	
	 	win.hide(null); // null to "unset" animation target
        win.destroy();	
	},
	
	show: function () {
	
		this.winname = 'uploadWindow'+this.pid;
		var upWindow = Ext.get(this.winname);
		
		if (!upWindow) {
			this.uploadId = uniqueId(currentUser);
			
	        upWindow = new Ext.Window({
	        	id: this.winname,
	            title: _('File Upload'),
	            closable:true,
	            width:600,
	            height:350,
	            iconCls: 'icon-upload',
	            plain:true,
	            layout: 'border',
	            items: [this.getUploadPanel(), this.getUploadGrid()],
	            manager: MyDesktop.getDesktop().getManager(),
	       });

			var ds = this.getDataStore()
			this.getUploadPanel().on({
				'allfinished': {
					fn: function() {
							ds.load();
						}
				}
			});	
	       
	        upWindow.parent = this;
	       	upWindow.on({
	       		'beforeclose': {
	       			fn: function(win) {
                		if (win.parent.getDataStore().getCount()>0) {
                			if (win.parent.getDataStore().reader.jsonData.totalCount>0) {
						        Ext.Msg.confirm(_('Confirm'),
						        	_('If you cancel now all uploaded items will will be deleted. Confirm?'),
						        			function(btn) {
												if (btn=="yes") {
													win.parent.cancel(win);
												} 
											} 
									);
							} else {
								win.parent.cancel(win);
							}
							return false;
                		}	
	       			}
	       		}
	       	
	       	});
	       	
	       	//this.getUploadPanel().waitMsgTarget = '
		}
								
       upWindow.show();

		if (upWarnShow && (BrowserDetect.browser == "Konqueror")) {
			upWarnShow = false;
			Ext.Msg.warn(_('File upload does not work properly with your browser. We recommend to use Firefox instead.'));
		}
		
	},

});
/* ----------------------------- END UPLOAD PANEL ------------------------------------*/
/* ----------------------------- EDIT WINDOW ------------------------------------*/
Ext.extend(Verbum.list.EditWindow, Ext.util.Observable, {

    show : function(){
    	var scope = this;
    	var desktop = scope.desktop;
	    var formwin='filelistEdit_'+scope.filePid;
		var fileListEditWin = desktop.getWindow(formwin);

		var fileid = scope.grid.getStore().getAt(scope.selected).id;
		var filename = scope.grid.getStore().getAt(scope.selected).data.fileName;
		var translator = scope.grid.getStore().getAt(scope.selected).data.translator;
		var reviewer = scope.grid.getStore().getAt(scope.selected).data.reviewer;
		var statusId = scope.grid.getStore().getAt(scope.selected).data.statusId;
		
		if (fileListEditWin) {
			Ext.destroy(fileListEditWin);
		}
		
		var type;
		
		switch (currentUser) {
			case translator:
				if (statusId!=FILE_STATUS_LOCKED 
					&& statusId!=FILE_STATUS_TRANS 
					&& statusId!=FILE_STATUS_CHKPND) {
					type="2";
				} else {
					FileListStatusDS = fileStatusTransDs;
					type="assign_trans";
				}
				break;
			case reviewer:
				if (statusId!=FILE_STATUS_PROOF 
					&& statusId!=FILE_STATUS_DONE 
					&& statusId!=FILE_STATUS_CHKPND) {
					type="2";
				} else {
					FileListStatusDS = fileStatusRevDs;
					type="assign_rev";
				}
				break;
			default:
				type="1";
				break;
		}
		
		if (type!="1" && type!="2") {
			var fileListForm = new Ext.form.FormPanel({
		        url: scope.url,
		        labelWidth: 100,
		        height:140,
		        waitMsgTarget: true,
		        frame: true,
		        items: [{
		        	    xtype : "fieldset",
						autoHeight : true,
						items : [
							{
								xtype: 'combo',
								fieldLabel: _('New Status'),
								hiddenName: 'statusid',
								emptyText: _('Select a file status...'),
								editable: false,
								allowBlank: false,
								blankText: _('The field is required.'),
								forceSelection: true,
								triggerAction: 'all',
							   	store: FileListStatusDS,
							   	valueField: 'id',
							   	displayField: 'text',
							   	width: 170,
							   	loadingText: _('Please wait...'),
							   	mode: 'local'
							},{
								id: 'fileEditComment'+scope.filePid,
								xtype: 'textarea',
								fieldLabel: _('Comments'),
								name: 'comment',
								width: 170,
								maxLength: 255
							}]
		        }], 
				tbar: [{
					text: _('Save'),
					tooltip: _('Save'),
					iconCls: 'save',
					handler: function() {
							var selections = scope.grid.selModel.getSelections();
						  	var encoded_array = "[";
						  	for(i = 0; i< scope.grid.selModel.getCount(); i++){
						  		var ss = "{\"id\":\"" +selections[i].get('id') + "\",\"hash\":\"" + selections[i].get('chstamp') + "\"}";
								if (i==0) {
									encoded_array = encoded_array + ss;
								} else {
									encoded_array = encoded_array + "," + ss;
								}
						  	}
						  	encoded_array = encoded_array + "]";
	
		                	fileListForm.initFields();
	                		if (fileListForm.getForm().isValid()) {
	                    		fileListForm.getForm().submit({ 
		                        	method:'POST', 
		                        	waitTitle: _('Saving...'), 
		                        	waitMsg: _('Saving...'),
									params: {ids: encoded_array, pid: scope.filePid, op: 'save'},
			                        success:function(form, action){
			                        	obj = Ext.util.JSON.decode(action.response.responseText);
			                        	if (obj.ret!=undefined) scope.fireEvent("success",obj.ret.results);
			                        	else scope.fireEvent("success",[]);			                        	
			                        	fileListEditWin.close();
			                        },
			                        failure:function(form, action){ 
		                                obj = Ext.util.JSON.decode(action.response.responseText); 
			                        	if (obj.ret!=undefined) scope.fireEvent("failure",obj.ret.results);
			                        	else scope.fireEvent("failure",[]);			                        	
		                                Ext.Msg.error(obj.error);
		                                fileListEditWin.close(); 
			                        }                   	
	                    		});
	                		}
	                	}
				},/*{
					text: _('Free'),
					tooltip: _('Remove my assignation from this file'),
					iconCls: 'free',
					handler: function() {
							var selections = scope.grid.selModel.getSelections();
						  	var encoded_array = "[";
						  	for(i = 0; i< scope.grid.selModel.getCount(); i++){
						  		var ss = "{\"id\":\"" +selections[i].get('id') + "\",\"hash\":\"" + selections[i].get('chstamp') + "\"}";
								if (i==0) {
									encoded_array = encoded_array + ss;
								} else {
									encoded_array = encoded_array + "," + ss;
								}
						  	}
						  	encoded_array = encoded_array + "]";
	
						  	var util = new Verbum.Utilities();
							util.request({
								el: fileListForm.getEl(),
					            params: { 
					               action: "file_list", 
					               ids:  encoded_array,
					               op: 'free',
					               pid: scope.filePid,
					               comment: Ext.getCmp('fileEditComment'+scope.filePid).getValue()
					              }											
							});

							util.on({
								'done': function(response) {
		                        	obj = Ext.util.JSON.decode(response.responseText);
		                        	if (obj.ret!=undefined) scope.fireEvent("success",obj.ret.results);
		                        	else scope.fireEvent("success",[]);
								},
								'fail': function(response) {
	                                obj = Ext.util.JSON.decode(response.responseText); 
		                        	if (obj.ret!=undefined) scope.fireEvent("failure",obj.ret.results);
		                        	else scope.fireEvent("failure",[]);
								},
								'hide': function() {
									fileListEditWin.close();
								}
							});		                	

	                	}
				}*/				
				]		        	
			});        	
	
		    fileListEditWin = desktop.createWindow({
		            id: formwin,
		            layout:'fit',
		            title: String.format(_('Set Status For {0}'),filename),
		            width:350,
		            height:200,
		            resizable: false,
		            maximizable: false,
		            items: fileListForm,
			    });
			    	
			fileListEditorWindows[0] = fileListEditWin;
	 		fileListEditWin.show();    			
		} else {
			if (type=="1") {
				//Ext.Msg.message(_('You are not the translator nor the reviewer of this file.'));
				scope.fireEvent("unassigned", scope);	
			} else {
				Ext.Msg.message(_('This file is not in the correct status to be edited.'));
			}
						
		}	
    
    }
});

function showFileHistory(grid, selected, pid) {
	var winname='filehistory'+pid;
	var fileHistoryWin = Ext.get(winname);
	
	if (fileHistoryWin) {
		Ext.destroy(fileHistoryWin);
	}
	
	var fileid = grid.getStore().getAt(selected).id;
	var filename = grid.getStore().getAt(selected).data.fileName;
	
	var fileHistoryDS = new Ext.data.Store({
		pruneModifiedRecords: true,
		remoteSort: false,
		proxy: new Ext.data.HttpProxy({
			url: getMainUrl(),
			method: 'POST'
			}),
			baseParams: {action: 'file_history', pid: pid, id: fileid},
			reader: new Ext.data.JsonReader({
				root: 'results',
				id: 'id'
			},[
			{name: 'comment',type:'string'},
			{name: 'statusId',type:'string',mapping:'statusid'},
			{name: 'userId',type:'string',mapping:'userid'},
			{name: 'lastUpdate',type:'string',mapping:'date'},
			{name: 'action',type:'string'},
			]),
			sortInfo: {field: 'lastUpdate',direction:'DESC'}
	});
    
	var fileHistoryCM = new Ext.grid.ColumnModel(
			[{
				header: _('Status'),
				readOnly: true,
				dataIndex: 'statusId',
				hidden: false,
				renderer: statusRender
			},
			{
				header: _('Last Update'),
				readOnly: true,
				dataIndex: 'lastUpdate',
				hidden: false,
				renderer: renderUserDate
			},{
				header: _('User'),
				readOnly: true,
				dataIndex: 'userId',
				hidden: false
			},{
				header: _('Action'),
				readOnly: true,
				dataIndex: 'action',
				renderer: translate,
				hidden: false
			},{
				header: _('Comments'),
				readOnly: true,
				dataIndex: 'comment',
				hidden: false
			}]
	);
	
	fileHistoryCM.defaultSortable = true;

	var fileHistoryEd = new Ext.grid.GridPanel({
		id: 'fileHistGrid',
		loadMask: {msg: _('Loading...')},
		store: fileHistoryDS,
		cm: fileHistoryCM,
		view: new Ext.grid.GridView()
	});

    fileHistoryWin = new Ext.Window({
        id: winname,
        title: String.format(_('History {0}'),filename),
        layout:'fit',
        width:460,
        height:230,
        resizable: true,
        maximizable: false,
        iconCls: 'history',
        items: fileHistoryEd,
        manager: MyDesktop.getDesktop().getManager(),
    });

	fileListEditorWindows[fileListEditorWindows.length] = fileHistoryWin;

	

	fileHistoryDS.on({
		'load': {
			fn: function() {
					if (this.totalLength==0) 
						fileHistoryEd.el.mask(_('No records available'),'ext-el-mask-msg');
				}
			}
	});	

    fileHistoryWin.show();	
	fileHistoryDS.load();
}

MyDesktop.FileListModule = Ext.extend(Ext.app.Module, {

	addAssign: function() {
		return {}
	},
	
    createWindow : function(src){

        var desktop = this.app.getDesktop();
        var winname = src.windowId;
        var win = desktop.getWindow(winname);
		var filePid = src.filePid;
		
        if(!win){
        	/* SET PREF */
        	var showListColors = true;
			if (getPref("showListColors")!=null) {
				showListColors = getPref("showListColors");
			}
			var lastQFilter = 'all';
			if (getPref("qFilter")!=null) {
				lastQFilter = getPref("qFilter");
			}			
			var fileListSize = DEFAULT_LIST_SIZE;
			if (getPref("fileListSize")!=null) {
				fileListSize = parseInt(getPref("fileListSize"));
			}
			var fieldSort = 'name';
			var fieldName = 'fileName';
			var dirSort = 'ASC';
			if (getPref("fileSortField")!=null && getPref("fileSortDir")!=null) {
				fieldName = getPref("fileSortName");
				fieldSort = getPref("fileSortField");
				dirSort = getPref("fileSortDir");				
			}
			/* - */
        	var FileListDS;
			var FileListCM;
			var FileListEd;

		    var sprjList = new Ext.data.JsonStore({
		        url: getMainUrl(),
		        method: 'POST',
		        baseParams: {action: 'system_list', op: 'sprj', id: filePid},
		        autoLoad: false,
		        root: 'results',
		        id: 'id',
		        fields:[
		        	{name: 'id'},
		            {name: 'text', mapping : 'name'}
		        ]
		    });
			
		    sprjList.load();			
			
   			FileListDS = new Ext.data.Store({
				pruneModifiedRecords: true,
				remoteSort: true,
				proxy: new Ext.data.HttpProxy({
					url: getMainUrl(),
					method: 'POST'
					}),
				baseParams: {action: 'file_list', pid: filePid, q: lastQFilter},
				reader: new Ext.data.JsonReader({
					root: 'results',
					totalProperty: 'totalCount',
					id: 'id'
				},DefFile)
			});
			
			FileListSM = new Ext.grid.CheckboxSelectionModel(
			);
			
			var FileListGridView = new Ext.grid.GridView({
				getRowClass : function (row, index) { 
					var cls = ''; 
					if (showListColors) {
						if (row.data.untranslated==='' || row.data.fuzzy==='') {
							cls = '';
						} else if (row.data.untranslated>0) {
							cls = 'untranslated-row';
						} else if (row.data.fuzzy>0) {
							cls = 'fuzzy-row';
						} else {
							cls = '';
						}
					}
					return cls; 
			   } 
			});
			
			FileListCM = new Ext.grid.ColumnModel(
				[FileListSM,
				{
					header: _('Status'),
					readOnly: true,
					dataIndex: 'statusId',
					hidden: false,
					renderer: statusRender
				},
				{
					header: _('Filename'),
					readOnly: true,
					dataIndex: 'fileName',
					hidden: false
				},{
					header: _('Translator'),
					readOnly: true,
					dataIndex: 'translator',
					hidden: false
				},{
					header: _('Reviewer'),
					readOnly: true,
					dataIndex: 'reviewer',
					hidden: false
				},{
					header: _('Project'),
					readOnly: true,
					dataIndex: 'prjname',
					hidden: true
				},{
					header: _('Last Update'),
					readOnly: true,
					dataIndex: 'lastUpdate',
					hidden: true,
					renderer: renderUserDate
				},{
					header: _('Total'),
					readOnly: true,
					hidden: true,
					sortable: false,
					align: 'right',
					renderer: createTotalColumn
				},{
					header: _('Translated'),
					readOnly: true,
					dataIndex: 'translated',
					hidden: true,
					align: 'right'
				},{
					header: _('Untranslated'),
					readOnly: true,
					dataIndex: 'untranslated',
					hidden: false,
					align: 'right'
				},{
					header: _('Fuzzy'),
					readOnly: true,
					dataIndex: 'fuzzy',
					hidden: false,
					align: 'right'
				},{
					header: _('Comments'),
					readOnly: true,
					dataIndex: 'comment',
					hidden: true,
					width: 100
				}]
			);
			
			FileListCM.defaultSortable = true;

			var filters = new Ext.ux.grid.GridFilters({
					menuFilterText: _('Filter'),
					filters:[
					{type: 'list', dataIndex: 'statusId', 
						options: getStatusFilter(), phpMode: true, fieldName: 'statusid'},
					{type: 'string',  dataIndex: 'fileName', fieldName: 'name'},
					{type: 'string',  dataIndex: 'translator'},
					{type: 'string',  dataIndex: 'reviewer'},
					{type: 'list',  dataIndex: 'prjname',
						store: sprjList, phpMode: true, loadOnShow: false},
					//{type: 'date',  dataIndex: 'lastUpdate', dateFormat: 'Y-m-d H:i', beforeText: _('Before'), afterText: _('After'), onText: _('On')},
					//{type: 'numeric',  dataIndex: 'translated'},
					//{type: 'numeric',  dataIndex: 'untranslated'},
					//{type: 'numeric',  dataIndex: 'fuzzy'},
					//{type: 'string',  dataIndex: 'comment'},
					],
					local: false
			});
			
			FileListBottomBar = new Ext.PagingToolbar({
				            pageSize: fileListSize,
				            store: FileListDS,
				            displayInfo: true,
				            emptyMsg: _('No files to display'),
				            items:[
				                '-',
				                {
								xtype: 'combo',
								editable: false,
								//forceSelection: true,
								triggerAction: 'all',
							   	store: getPageSizeList(),
							   	//mode: 'local',
							   	width: 50,
							   	value: fileListSize,
							   	listeners: {select: 
							   				function(combo,record,index) {
							   					fileListSize = combo.lastSelectionText;
							   					setPref("fileListSize",fileListSize);
							   					FileListBottomBar.pageSize = fileListSize;
							   					FileListDS.reload({params:{start:0, limit:fileListSize}});
							   				}
							   		}
				                },
			                	{
				                pressed: showListColors,
				                enableToggle:true,
				                text: _('Highlight untranslated & fuzzy'),
				                cls: 'x-btn-text-icon colors',
				                toggleHandler: function(btn, pressed) {
										showListColors = pressed;
										setPref("showListColors",pressed);
    									FileListEd.getView().refresh();
								}
            				}]
				        });
			
			FileListToolBar = new Ext.Toolbar({
				            items:[{
				                text: _('Assign'),
				                tooltip: _('Change the assign properties of the selected files'),
				                cls: 'x-btn-text-icon assign',
				                handler: function(btn, pressed) {
								        if (checkRO(filePid)) {
									        if (fileListGrants!="") {
										        if (FileListEd.selModel.getCount()>0) {
										        	showAssignWindow(FileListEd, desktop, filePid)
												} else {
													Ext.Msg.message(_('Please, select an item from the list.'));
												}								        	
									        } else {
									        	Ext.Msg.error(_('Sorry, you do not have the appropiated permission to perfom this action.'))
									        }
								        }
					                }
		    					},
								{
								text: _('Release'),
								tooltip: _('Unlock the selected files. So others can take it.'),
								iconCls: 'free',
								handler: function() {
										if (checkRO(filePid)) {
											freeSelected(FileListEd, filePid);
										}
									}
								},"-", {
				                text: _('Upload'),
				                cls: 'x-btn-text-icon uploadfile',
				                tooltip: _('Upload a set of .po files'),
				                handler: function(btn, pressed) {
					                	if (checkRO(filePid)) {
											var upPanel = new Verbum.list.UploadPanel({pid: filePid});
											upPanel.show(); 
		
											upPanel.on({
												'success': {
													fn: function (s){
															FileListDS.reload();
								    					}
												}
											});
					                	}			
									}
								}, {
				                text: _('Download'),
				                cls: 'x-btn-text-icon downloadfile',
				                tooltip: _('Download the selected files'),
				                handler: function(btn, pressed) {
							        if (FileListEd.selModel.getCount()>0) {
										var selections = FileListEd.selModel.getSelections();
									  	var encoded_array = "";
									  	for(i = 0; i< FileListEd.selModel.getCount(); i++){
									  		if (i>0) {
									  			encoded_array = encoded_array + ":";
									  		}
											encoded_array = encoded_array + selections[i].json.id;
									  	}

										lMask = new Ext.LoadMask(FileListEd.el, {msg: _('Please wait...'), removeMask: true});
								    	lMask.show();
		
										Ext.Ajax.request({ 
										            waitMsg: _('Please wait...'),
										            url: getMainUrl(),
										            params: { 
										               action: "download_file", 
										               ids:  encoded_array,
										               pid: filePid
										              }, 
										            success: function(response){
										            	obj = Ext.util.JSON.decode(response.responseText);
										            	if (obj.success==false) {
										            		Ext.Msg.alert(_('Error'), obj.error);
										            	} else {
										            		fetchFile(obj.ret);	
										            	}
										            },
													callback: function ( options, success, response ) { 
														lMask.hide();
													}
									   });	
									} else {
										Ext.Msg.message(_('Please, select an item from the list.'));
									}
								}
								},'-',
								{
									text: _('Quick Filter')+" ",
									xtype: 'label'
								},
								{
									xtype: 'combo',
									editable: false,
									triggerAction: 'all',
									store: [['all',_('All')],['mf',_('My Files')],['un',_('Untranslated/Fuzzy')]],
									width: 120,
									value: lastQFilter,
									listeners: {select: 
										function(combo,record,index) {
											lastQFilter = record.data.value;
											setPref("qFilter",lastQFilter);
											FileListDS.baseParams['q']=lastQFilter;
											filters.clearFilters(true);
											FileListDS.reload({params:{start:0, limit:fileListSize}});
										}
									}
								},'-',{
								text: _('Export'),
								iconCls: 'table_save',
								handler: function() {
										var util = new Verbum.Utilities();
										util.request({
								            params: { 
								               el: win.getEl(),
								               action: "file_list", 
								               pid: filePid,
								               op: 'gal'
								              }											
										});
										
										util.on({
											'done': function(response) {
								            	obj = Ext.util.JSON.decode(response.responseText);
							            		fetchFile(obj.ret[0].file,"si",obj.ret[0].name,"text/csv");
											}
										})
									}
								},'->',{
					            	text:_('Show statistics'),
					            	iconCls:'chart-icon',
					            	scope: this,
					            	handler: function() {
					            		var wname = "stats-win"+filePid;
					            		var container = "stats-container-"+filePid;
					            		win = Ext.get(wname);
					            		if (!win) {
									        win = desktop.createWindow({
								                id: wname,
								                title: String.format(_('Statistics for {0}'),src.text),
								                width:480,
								                height:200,
								                iconCls: 'chart-icon',
								                border:false,
								                constrainHeader:true,
								                layout: 'fit',
								                maximizable: false,
								                items: new Ext.Panel({
							                        items: [{
						    	                        html : '<div id="'+container+'"></div>',
						        	                    border:false
						            	            }
						            	            ]})
								           	});
					            		}

										var store = new Ext.data.JsonStore({
										    url: getMainUrl(),
										    method: 'POST',
										    baseParams: {action: 'system_list', op: "stats", pid: filePid},
										    autoLoad: false,
										    root: 'results',
										    fields:[
												{name: 'translated',type:'int'},
												{name: 'untranslated',type:'int'},
												{name: 'fuzzy',type:'int'},
										    ]
										});					            		

										var lMask = new Ext.LoadMask(win.getEl(), {msg: _('Loading...') , removeMask: true});
										
   										store.on({
											'load': function(ds, records, opt) {
												lMask.hide();
										        var data = new google.visualization.DataTable();
										        
										        var translated = parseInt(records[0].data.translated);
										        var untrans = parseInt(records[0].data.untranslated);
										        var fuzzy = parseInt(records[0].data.fuzzy);
										        var total = translated + untrans + fuzzy;
										        
										        var pt = (translated * 100) / total;
										        var pu = (untrans * 100) / total;
										        var pf = (fuzzy * 100) / total;
										        
										        data.addColumn('string', _('Project'));
										        data.addColumn('number', String.format(_('Translated {0}%'),new Number(pt).toFixed(2)));
										        data.addColumn('number', String.format(_('Fuzzy {0}%'),new Number(pf).toFixed(2)));
										        data.addColumn('number', String.format(_('Untranslated {0}%'),new Number(pu).toFixed(2)));
										        
										        /*data.addColumn('string', "");
										        data.addColumn('number', "");
										        data.addRows(3);
												data.setValue(0, 0, _/('Translated'));
										        data.setValue(0, 1, records[0].data.translated);
												data.setValue(1, 0, _/('Untranslated'));
										        data.setValue(1, 1, records[0].data.untranslated);
												data.setValue(2, 0, _/('Fuzzy'));
										        data.setValue(2, 1, records[0].data.fuzzy);*/
										        data.addRows(records.length);
										        
										        //for (var i=0;i<records.length;i++) {
											        data.setValue(0, 0, "");
											        data.setValue(0, 1, records[0].data.translated);
											        data.setValue(0, 2, records[0].data.fuzzy);
											        data.setValue(0, 3, records[0].data.untranslated);
										        //}
										        
										        var chart = new google.visualization.BarChart(document.getElementById(container));
										        //var chart = new google.visualization.PieChart(document.getElementById(container));
										        chart.draw(data, {width: 450, height: 160, is3D: true, isStacked: true, colors: ['#5FD53B', '#4183F4', '#5E5B5B'] });
												
											},
											'loadexception': function() {
												lMask.hide();
											}
										}) 

							           	win.on({
							           		'show': function() {
	    										lMask.show();
	    										store.load();
							           		}
							           	});
							           	
							           	win.show(); 
					           		}
					            }]
				        });

			FileListEd = new Ext.grid.GridPanel({
				id: 'fileListGrid',
				//autoExpandColumn: 10,
				loadMask: {msg: _('Loading...')},
				store: FileListDS,
				cm: FileListCM,
				selModel: FileListSM,
				view: FileListGridView,
				plugins: filters,
				bbar: FileListBottomBar,
				tbar: FileListToolBar
			});

			FileListEd.on('rowcontextmenu', onFileListContextMenu, {ds: FileListDS, desktop: desktop, filePid: filePid});

			FileListEd.on({
				'rowdblclick': {
					fn: function (grid, rowIndex, e){
							if (checkRO(filePid)) {
								grid.selModel.clearSelections();
								grid.selModel.selectRow(rowIndex);
								editSelected(grid, rowIndex, desktop, filePid, FileListEd.getStore())
							}
    					}
				},
				'sortchange': {
					fn: function(grid,sortInfo) {
						if (sortInfo.sortField!=undefined) {
							setPref("fileSortName",sortInfo.field);
							setPref("fileSortField",sortInfo.sortField);
							setPref("fileSortDir",sortInfo.direction);	
						}
					}
				}
			});

			win = desktop.createWindow({
				id: winname,
				closable:true,
				width:640,
				height:480,
				plain:true,
				layout: 'fit',
				iconCls: 'plugin',
				items: FileListEd,
				title: src.title
            });

			win.on({
				'close': {
					fn: function() {
						for (i=0;i<fileListEditorWindows.length;i++) {
							Ext.destroy(fileListEditorWindows[i]);	
						}
					}
				}
			});
			
			FileListDS.sortInfo = {field: fieldName, sortField: fieldSort, direction: dirSort};
            FileListDS.load({params:{start:0, limit:fileListSize}});

			fileStatusTransDs.load();
			fileStatusRevDs.load();

        }
        win.show();
    }
});

MyDesktop.FileListSubModule = Ext.extend(MyDesktop.FileListModule, {
	id:'filelistmenu',
    init : function(){
		
	    FileListProjectDS.each(function(record) {
				var elem = this;
				var title = record.data.name; 
				if (record.data.statsupdated!="") {
					title += " " + String.format(_('[Statistics updated on {0}]'),record.data.statsupdated);
				}
				if (record.data.ro) {
					title = _('- Read Only -') + " " + title;
				}
				FileListMenu.add(
					{text: record.data.name,
					 filePid: record.data.id,
					 handler: elem.createWindow,
					 scope: elem,
					 windowId: 'filelist_' + record.data.id,
					 iconCls: 'plugin',
					 title: title
					}
					);		
			}, this);
    
        this.launcher = {
            text: _('File Manager'),
            iconCls: 'icon-grid',
            handler: function() {
				return false;
			},
            menu: FileListMenu
        }
    }
});